<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"matian.connorma.cn","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="最近为项目整合动态多数据源，忽然想到一个问题：每种数据库需要特定的JDBC，在使用的时候只需要引入对应依赖包，那么java包是怎么引用的呢？这里至少需要解决这样的问题：  必须是由java定义统一接口，各个数据库厂商或者开源社区针对数据库提供实现，不然适配这么多数据库是完全不可能也不合理的，毫无扩展性可言 只能在运行时加载JDBC驱动实现类，所以需要提供一种方式，使得类加载器能够找到各个驱动的实现">
<meta property="og:type" content="article">
<meta property="og:title" content="从JDBC Driver看java SPI">
<meta property="og:url" content="http://matian.connorma.cn/372d5b3e.html">
<meta property="og:site_name" content="马天">
<meta property="og:description" content="最近为项目整合动态多数据源，忽然想到一个问题：每种数据库需要特定的JDBC，在使用的时候只需要引入对应依赖包，那么java包是怎么引用的呢？这里至少需要解决这样的问题：  必须是由java定义统一接口，各个数据库厂商或者开源社区针对数据库提供实现，不然适配这么多数据库是完全不可能也不合理的，毫无扩展性可言 只能在运行时加载JDBC驱动实现类，所以需要提供一种方式，使得类加载器能够找到各个驱动的实现">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-07-29T14:22:39.000Z">
<meta property="article:modified_time" content="2024-01-25T12:19:17.209Z">
<meta property="article:author" content="马天">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://matian.connorma.cn/372d5b3e.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>从JDBC Driver看java SPI | 马天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">马天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://matian.connorma.cn/372d5b3e.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="马天">
      <meta itemprop="description" content="程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="马天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          从JDBC Driver看java SPI
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-07-29 22:22:39" itemprop="dateCreated datePublished" datetime="2022-07-29T22:22:39+08:00">2022-07-29</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>最近为项目整合动态多数据源，忽然想到一个问题：每种数据库需要特定的JDBC，在使用的时候只需要引入对应依赖包，那么java包是怎么引用的呢？这里至少需要解决这样的问题：</p>
<ul>
<li>必须是由java定义统一接口，各个数据库厂商或者开源社区针对数据库提供实现，不然适配这么多数据库是完全不可能也不合理的，毫无扩展性可言</li>
<li>只能在运行时加载JDBC驱动实现类，所以需要提供一种方式，使得类加载器能够找到各个驱动的实现类完成加载</li>
</ul>
<p>带着问题浏览了java.sql下的关键类，了解到这种机制称为SPI，即Service Provider Interface。这种模式适合为框架提供扩展点，不难联想到，spring通过spring.factories加载类也是SPI模式的应用</p>
<span id="more"></span>

<h2 id="java-sql-DriverManager加载驱动类流程"><a href="#java-sql-DriverManager加载驱动类流程" class="headerlink" title="java.sql.DriverManager加载驱动类流程"></a>java.sql.DriverManager加载驱动类流程</h2><p>DriverManager类为我们提供了一个使用SPI的很好的样例，所以还是从这里入手，将java SPI作为黑盒，先看下基于SPI完成jdbc驱动类加载和使用的整体流程</p>
<p>java.sql下关于驱动加载的类是java.sql.DriverManager和java.sql.Driver，其中，Driver类是为不同驱动提供的统一接口：The interface that every driver class must implement，而驱动类的加载是在DriverManager类中进行的</p>
<p>通过类的注释可以了解到，指定驱动类有方式：</p>
<ol>
<li>通过JVM参数：the DriverManager class will attempt to load the driver classes referenced in the “jdbc.drivers” system property</li>
<li>通过JAVA标准的SPI机制：The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF&#x2F;services&#x2F;java.sql.Driver</li>
</ol>
<p>加载驱动类的关键代码在loadInitialDrivers函数中：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">loadInitialDrivers</span><span class="params">()</span> &#123;</span><br><span class="line">    String drivers;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 读取JVM参数指定的驱动类类名</span></span><br><span class="line">        drivers = AccessController.doPrivileged(<span class="keyword">new</span> <span class="title class_">PrivilegedAction</span>&lt;String&gt;() &#123;</span><br><span class="line">            <span class="keyword">public</span> String <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> System.getProperty(<span class="string">&quot;jdbc.drivers&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        drivers = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// If the driver is packaged as a Service Provider, load it.</span></span><br><span class="line">    <span class="comment">// Get all the drivers through the classloader</span></span><br><span class="line">    <span class="comment">// exposed as a java.sql.Driver.class service.</span></span><br><span class="line">    <span class="comment">// ServiceLoader.load() replaces the sun.misc.Providers()</span></span><br><span class="line"></span><br><span class="line">    AccessController.doPrivileged(<span class="keyword">new</span> <span class="title class_">PrivilegedAction</span>&lt;Void&gt;() &#123;</span><br><span class="line">        <span class="keyword">public</span> Void <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 通过SPI机制加载jar包中指定的驱动类</span></span><br><span class="line">            ServiceLoader&lt;Driver&gt; loadedDrivers = ServiceLoader.load(Driver.class);</span><br><span class="line">            Iterator&lt;Driver&gt; driversIterator = loadedDrivers.iterator();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/* Load these drivers, so that they can be instantiated.</span></span><br><span class="line"><span class="comment">             * It may be the case that the driver class may not be there</span></span><br><span class="line"><span class="comment">             * i.e. there may be a packaged driver with the service class</span></span><br><span class="line"><span class="comment">             * as implementation of java.sql.Driver but the actual class</span></span><br><span class="line"><span class="comment">             * may be missing. In that case a java.util.ServiceConfigurationError</span></span><br><span class="line"><span class="comment">             * will be thrown at runtime by the VM trying to locate</span></span><br><span class="line"><span class="comment">             * and load the service.</span></span><br><span class="line"><span class="comment">             *</span></span><br><span class="line"><span class="comment">             * Adding a try catch block to catch those runtime errors</span></span><br><span class="line"><span class="comment">             * if driver not available in classpath but it&#x27;s</span></span><br><span class="line"><span class="comment">             * packaged as service and that service is there in classpath.</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">try</span>&#123;</span><br><span class="line">                <span class="keyword">while</span>(driversIterator.hasNext()) &#123;</span><br><span class="line">                    driversIterator.next();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span>(Throwable t) &#123;</span><br><span class="line">            <span class="comment">// Do nothing</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;DriverManager.initialize: jdbc.drivers = &quot;</span> + drivers);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (drivers == <span class="literal">null</span> || drivers.equals(<span class="string">&quot;&quot;</span>)) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    String[] driversList = drivers.split(<span class="string">&quot;:&quot;</span>);</span><br><span class="line">    println(<span class="string">&quot;number of Drivers:&quot;</span> + driversList.length);</span><br><span class="line">    <span class="keyword">for</span> (String aDriver : driversList) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            println(<span class="string">&quot;DriverManager.Initialize: loading &quot;</span> + aDriver);</span><br><span class="line">            <span class="comment">// 使用类名加载类</span></span><br><span class="line">            Class.forName(aDriver, <span class="literal">true</span>,</span><br><span class="line">                    ClassLoader.getSystemClassLoader());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">            println(<span class="string">&quot;DriverManager.Initialize: load failed: &quot;</span> + ex);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在之前关于类加载器的文章<a href="/94439062.html" title="java类加载器问题思考与简单模拟热部署">java类加载器问题思考与简单模拟热部署</a>中了解过，mysql等jdbc Driver类中，通过static代码块的方式，在Driver类加载时完成初始化，关键的代码为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> &#123;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		java.sql.DriverManager.registerDriver(<span class="keyword">new</span> <span class="title class_">Driver</span>());</span><br><span class="line">	&#125; <span class="keyword">catch</span> (SQLException E) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;Can&#x27;t register driver!&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里进行了Driver类的实例化，最终调用回到了DriverManager类的registerDriver方法，这里关键的代码是记录了Driver实现类的信息</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Register the driver if it has not already been added to our list */</span></span><br><span class="line">        <span class="keyword">if</span>(driver != <span class="literal">null</span>) &#123;</span><br><span class="line">            registeredDrivers.addIfAbsent(<span class="keyword">new</span> <span class="title class_">DriverInfo</span>(driver, da));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>而在对数据库进行操作时，可以看到，getConnection()方法中有遍历选取Driver实现类的步骤：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 遍历所有已注册的Driver实现类，选择与当前连接的数据库匹配的执行操作</span></span><br><span class="line"><span class="keyword">for</span>(DriverInfo aDriver : registeredDrivers) &#123;</span><br><span class="line">            <span class="comment">// If the caller does not have permission to load the driver then</span></span><br><span class="line">            <span class="comment">// skip it.</span></span><br><span class="line">            <span class="keyword">if</span>(isDriverAllowed(aDriver.driver, callerCL)) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    println(<span class="string">&quot;    trying &quot;</span> + aDriver.driver.getClass().getName());</span><br><span class="line">                    <span class="type">Connection</span> <span class="variable">con</span> <span class="operator">=</span> aDriver.driver.connect(url, info);</span><br><span class="line">                    <span class="keyword">if</span> (con != <span class="literal">null</span>) &#123;</span><br><span class="line">                        <span class="comment">// Success!</span></span><br><span class="line">                        println(<span class="string">&quot;getConnection returning &quot;</span> + aDriver.driver.getClass().getName());</span><br><span class="line">                        <span class="keyword">return</span> (con);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (SQLException ex) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (reason == <span class="literal">null</span>) &#123;</span><br><span class="line">                        reason = ex;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                println(<span class="string">&quot;    skipping: &quot;</span> + aDriver.getClass().getName());</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>


<p>所以，整个的流程是：DriverManager类通过SPI机制加载所有的Driver实现类 –&gt; Driver实现类通过类加载机制，在加载时将自身信息注册到DriverManager –&gt; 连接数据库时，DriverManager遍历所有注册的Driver实现类，选取匹配的实现类执行</p>
<h2 id="java-SPI"><a href="#java-SPI" class="headerlink" title="java SPI"></a>java SPI</h2><p>下面继续来看下java SPI的使用方式</p>
<p>基本的使用很简单，首先定义接口和实现类，为了方便实现类直接一起放在了源代码里：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接口MyInterface com.connorma.spi_learn.MyInterface</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">MyInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">func</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实现类A com.connorma.spi_learn.MyInterfaceA</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyInterfaceA</span> <span class="keyword">implements</span> <span class="title class_">MyInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.println(MyInterfaceA.class.getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">func</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;A&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 实现类B com.connorma.spi_learn.MyInterfaceB</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyInterfaceB</span> <span class="keyword">implements</span> <span class="title class_">MyInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.println(MyInterfaceB.class.getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">func</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;B&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在resources目录下新建目录META-INF&#x2F;services，添加文件“com.connorma.spi_learn.MyInterface”，即接口类的全限定名，文件内容写入：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">com.connorma.spi_learn.MyInterfaceA</span><br><span class="line">com.connorma.spi_learn.MyInterfaceB</span><br></pre></td></tr></table></figure>

<p>即将两个实现类的全限定名按行写入</p>
<p>这样打包为jar之后，可以看到jar包内包含了META-INF&#x2F;services&#x2F;com.connorma.spi_learn.MyInterface文件</p>
<p>在代码中可以使用ServiceLoader类加载：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">ServiceLoader&lt;MyInterface&gt; serviceLoader = ServiceLoader.load(MyInterface.class);</span><br><span class="line"></span><br><span class="line">Iterator&lt;MyInterface&gt; iterator = serviceLoader.iterator();</span><br><span class="line"><span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">    <span class="type">MyInterface</span> <span class="variable">itf</span> <span class="operator">=</span> iterator.next();</span><br><span class="line">    itf.func();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行以上代码则输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">com.connorma.spi_learn.MyInterfaceA</span><br><span class="line">A</span><br><span class="line">com.connorma.spi_learn.MyInterfaceB</span><br><span class="line">B</span><br></pre></td></tr></table></figure>

<p>这只是一个简单的使用演示，真正使用的使用方式，那么需要像DriverManager一样，处理实现类的选择和使用等问题</p>
<h3 id="ServiceLoader的加载方式"><a href="#ServiceLoader的加载方式" class="headerlink" title="ServiceLoader的加载方式"></a>ServiceLoader的加载方式</h3><p>从上面演示代码的输出可以看出，ServiceLoader类在调用load函数时并不会完成实现类的加载，而是在以懒加载的形式，在通过迭代器获取类实例时才加载的——实际上看代码可以发现，ServiceLoader中定义了内部类LazyIterator，是在迭代时才去读取META-INF&#x2F;services下的文件、加载类的</p>
<p>LazyIterator类的hasNext()方法最终调用了内部的hasNextService()方法，返回下一个实现类的类名，关键代码为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">fullName</span> <span class="operator">=</span> PREFIX + service.getName();</span><br><span class="line"><span class="keyword">if</span> (loader == <span class="literal">null</span>)</span><br><span class="line">    configs = ClassLoader.getSystemResources(fullName);</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    configs = loader.getResources(fullName);</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> ((pending == <span class="literal">null</span>) || !pending.hasNext()) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!configs.hasMoreElements()) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    pending = parse(service, configs.nextElement());</span><br><span class="line">&#125;</span><br><span class="line">nextName = pending.next();</span><br></pre></td></tr></table></figure>

<p>而LazyIterator类的next()方法最终调用了内部的nextService()方法，在其中进行了类的加载和实例化，关键代码为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">cn</span> <span class="operator">=</span> nextName;</span><br><span class="line">nextName = <span class="literal">null</span>;</span><br><span class="line">Class&lt;?&gt; c = <span class="literal">null</span>;</span><br><span class="line"><span class="comment">// 加载实现类</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    c = Class.forName(cn, <span class="literal">false</span>, loader);</span><br><span class="line">&#125; <span class="keyword">catch</span> (ClassNotFoundException x) &#123;</span><br><span class="line">    fail(service,</span><br><span class="line">            <span class="string">&quot;Provider &quot;</span> + cn + <span class="string">&quot; not found&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> (!service.isAssignableFrom(c)) &#123;</span><br><span class="line">    fail(service,</span><br><span class="line">             <span class="string">&quot;Provider &quot;</span> + cn  + <span class="string">&quot; not a subtype&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 实现类实例化</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="type">S</span> <span class="variable">p</span> <span class="operator">=</span> service.cast(c.newInstance());</span><br><span class="line">    providers.put(cn, p);</span><br><span class="line">    <span class="keyword">return</span> p;</span><br><span class="line">&#125; <span class="keyword">catch</span> (Throwable x) &#123;</span><br><span class="line">    fail(service,</span><br><span class="line">            <span class="string">&quot;Provider &quot;</span> + cn + <span class="string">&quot; could not be instantiated&quot;</span>,</span><br><span class="line">        x);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="java-SPI的问题"><a href="#java-SPI的问题" class="headerlink" title="java SPI的问题"></a>java SPI的问题</h3><p>ServiceLoader类的实现简单清晰，但是真打算使用的时候，细细一想，感觉就是注释里说的：A simple service-provider loading facility.</p>
<p>ServiceLoader的实现并没有提供太多的自定义选项，功能上支持的很简单。</p>
<p>ServiceLoader只能一次性读取所有META-INF&#x2F;services下的文件，之后在迭代中依次加载类和实例化。这样，无法有效的指定加载某个或某种实现类，也存在类加载、实例化的资源消耗。设想一种场景：在使用jdbc驱动类中，虽然依赖同时引入了mysql、pg的驱动，但是希望在运行中可以指定加载某种数据库的驱动类；想实现这种方式，最容易想到的是在指定驱动类类名时可以通过键值对进行，比如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mysql=com.mysql.cj.jdbc.Driver</span><br><span class="line">postgresql=org.postgresql.Driver</span><br></pre></td></tr></table></figure>

<p>这样在运行时就可以根据配置参数决定要加载的实现类</p>
<p>但是，ServiceLoader类并没有开放这类自定义扩展的能力</p>
<p>这个例子并不太准确，毕竟mysql&#x2F;pg的驱动类并不是可以相互替换的实现，只是用于说明问题</p>
<h2 id="dubbo的SPI"><a href="#dubbo的SPI" class="headerlink" title="dubbo的SPI"></a>dubbo的SPI</h2><p>之前了解了java SPI后也并没有继续去看其他框架的扩展点设计，直到最近看到了dubbo的SPI实现，很好的解决了上文提到的java SPI的问题，提供了以下特性（from dubbo文档）：</p>
<ul>
<li>按需加载。Dubbo 的扩展能力不会一次性实例化所有实现，而是用哪个扩展类则实例化哪个扩展类，减少资源浪费。</li>
<li>增加扩展类的 IOC 能力。Dubbo 的扩展能力并不仅仅只是发现扩展服务实现类，而是在此基础上更进一步，如果该扩展类的属性依赖其他对象，则 Dubbo 会自动的完成该依赖对象的注入功能。</li>
<li>增加扩展类的 AOP 能力。Dubbo 扩展能力会自动的发现扩展类的包装类，完成包装类的构造，增强扩展类的功能。</li>
<li>具备动态选择扩展实现的能力。Dubbo 扩展会基于参数，在运行时动态选择对应的扩展类，提高了 Dubbo 的扩展能力。</li>
<li>可以对扩展实现进行排序。能够基于用户需求，指定扩展实现的执行顺序。</li>
<li>提供扩展点的 Adaptive 能力。该能力可以使的一些扩展类在 consumer 端生效，一些扩展类在 provider 端生效。</li>
</ul>
<p>在此学习了解下，这里使用的是dubbo 3.1的源代码</p>
<p>dubbo SPI的整体处理流程肯定还是相同的：首先查找、加载扩展类，然后完成类的实例化和后置处理（为扩展类进行依赖注入等）</p>
<h3 id="dubbo-SPI的使用"><a href="#dubbo-SPI的使用" class="headerlink" title="dubbo SPI的使用"></a>dubbo SPI的使用</h3><p>首先从用户视角看下如何使用dubbo SPI声明扩展类，相关的注解有：</p>
<ul>
<li>@Adaptive，自适应加载扩展类，一般在扩展点接口的函数上使用，需要函数包含一个org.apache.dubbo.common.URL类型的参数，将在运行时根据URL中的参数值确定加载的实现类</li>
<li>@Activate，在扩展类上使用，可通过group、value配置扩展类的加载规则，可通过order指定扩展类的加载次序</li>
</ul>
<h4 id="dubbo-SPI扩展类示例"><a href="#dubbo-SPI扩展类示例" class="headerlink" title="dubbo SPI扩展类示例"></a>dubbo SPI扩展类示例</h4><p>下面以一个示例说明dubbo SPI的使用方式。假设存在一个接口定义了发起网络请求的方法，扩展类分别实现了使用http、https协议的请求方式</p>
<p>为了方便演示定义一个接口用于扩展</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接口  com.connorma.dubbo_spi_learn.RequestInterface</span></span><br><span class="line"><span class="meta">@SPI(&quot;http&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">RequestInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">call</span><span class="params">(URL url)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，@SPI注解用于标记一个扩展点接口，http表示默认使用的扩展类的key</p>
<p>然后添加两个实现类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 实现类1  http=com.connorma.dubbo_spi_learn.HttpRequestCaller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HttpRequestCaller</span> <span class="keyword">implements</span> <span class="title class_">RequestInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.println(HttpRequestCaller.class.getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">call</span><span class="params">(URL url)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;do call with http, url: &quot;</span> + url.toFullString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实现类2  https=com.connorma.dubbo_spi_learn.HttpsRequestCaller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HttpsRequestCaller</span> <span class="keyword">implements</span> <span class="title class_">RequestInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.println(HttpsRequestCaller.class.getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">call</span><span class="params">(URL url)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;do call with https, url: &quot;</span> + url.toFullString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>并添加文件META-INF&#x2F;dubbo&#x2F;com.connorma.dubbo_spi_learn.RequestInterface，内容为：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">http=com.connorma.dubbo_spi_learn.HttpRequestCaller</span><br><span class="line">https=com.connorma.dubbo_spi_learn.HttpsRequestCaller</span><br></pre></td></tr></table></figure>

<p>文件内容是按行的键值对，为每个扩展类指定一个key；之前@SPI注解指定的默认扩展类是key为http的com.connorma.dubbo_spi_learn.HttpRequestCaller</p>
<p>执行代码，加载扩展类和调用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">ExtensionLoader&lt;RequestInterface&gt; loader = ExtensionLoader.getExtensionLoader(RequestInterface.class);</span><br><span class="line"></span><br><span class="line">Map&lt;String, String&gt; params1 = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">params1.put(<span class="string">&quot;type&quot;</span>, <span class="string">&quot;http&quot;</span>);</span><br><span class="line"><span class="type">URL</span> <span class="variable">url1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">URL</span>(<span class="string">&quot;test-call&quot;</span>, <span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>, params1);</span><br><span class="line"></span><br><span class="line">Map&lt;String, String&gt; params2 = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">params2.put(<span class="string">&quot;type&quot;</span>, <span class="string">&quot;https&quot;</span>);</span><br><span class="line"><span class="type">URL</span> <span class="variable">url2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">URL</span>(<span class="string">&quot;test-call&quot;</span>, <span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>, params2);</span><br><span class="line"></span><br><span class="line"><span class="type">RequestInterface</span> <span class="variable">defReqCaller</span> <span class="operator">=</span> loader.getDefaultExtension();</span><br><span class="line">defReqCaller.call(url1);</span><br><span class="line">defReqCaller.call(url2);</span><br></pre></td></tr></table></figure>

<p>输出为：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">com.connorma.dubbo_spi_learn.HttpRequestCaller</span><br><span class="line">com.connorma.dubbo_spi_learn.HttpsRequestCaller</span><br><span class="line">do call with http, url: test-call://localhost:8080?type=http</span><br><span class="line">do call with http, url: test-call://localhost:8080?type=http2</span><br></pre></td></tr></table></figure>

<p>这里演示的代码额外的引入了URL参数，实际在这个例子里并没有作用，可以结合使用@Adaptive的示例来看</p>
<h4 id="使用-Adaptive根据URL参数动态选用扩展类"><a href="#使用-Adaptive根据URL参数动态选用扩展类" class="headerlink" title="使用@Adaptive根据URL参数动态选用扩展类"></a>使用@Adaptive根据URL参数动态选用扩展类</h4><p>在以上的代码中提供了两个扩展类，key分别为http和https，并在接口定义时指定了默认使用key为http的扩展类</p>
<p>接下来将演示通过@Adaptive注解，根据URL携带的参数，动态选取扩展类</p>
<p>只需要为接口的方法上添加@Adaptive注解：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接口  com.connorma.dubbo_spi_learn.RequestInterface</span></span><br><span class="line"><span class="meta">@SPI(&quot;http&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">RequestInterface</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Adaptive(value = &quot;type&quot;)</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">call</span><span class="params">(URL url)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>加载扩展类时使用getAdaptiveExtension()方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">ExtensionLoader&lt;RequestInterface&gt; loader = ExtensionLoader.getExtensionLoader(RequestInterface.class);</span><br><span class="line"></span><br><span class="line">Map&lt;String, String&gt; params1 = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">params1.put(<span class="string">&quot;type&quot;</span>, <span class="string">&quot;http&quot;</span>);</span><br><span class="line"><span class="type">URL</span> <span class="variable">url1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">URL</span>(<span class="string">&quot;test-call&quot;</span>, <span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>, params1);</span><br><span class="line"></span><br><span class="line">Map&lt;String, String&gt; params2 = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">params2.put(<span class="string">&quot;type&quot;</span>, <span class="string">&quot;https&quot;</span>);</span><br><span class="line"><span class="type">URL</span> <span class="variable">url2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">URL</span>(<span class="string">&quot;test-call&quot;</span>, <span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>, params2);</span><br><span class="line"></span><br><span class="line"><span class="type">RequestInterface</span> <span class="variable">defReqCaller</span> <span class="operator">=</span> loader.getDefaultExtension();</span><br><span class="line">defReqCaller.call(url1);</span><br><span class="line">defReqCaller.call(url2);</span><br><span class="line"></span><br><span class="line"><span class="type">RequestInterface</span> <span class="variable">adaptiveReqCaller</span> <span class="operator">=</span> loader.getAdaptiveExtension();</span><br><span class="line">adaptiveReqCaller.call(url1);</span><br><span class="line">adaptiveReqCaller.call(url2);</span><br></pre></td></tr></table></figure>

<p>输出为：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">com.connorma.dubbo_spi_learn.HttpRequestCaller</span><br><span class="line">com.connorma.dubbo_spi_learn.HttpsRequestCaller</span><br><span class="line">do call with http, url: test-call://localhost:8080?type=http</span><br><span class="line">do call with http, url: test-call://localhost:8080?type=https</span><br><span class="line">call with adaptive extension:</span><br><span class="line">do call with http, url: test-call://localhost:8080?type=http</span><br><span class="line">do call with https, url: test-call://localhost:8080?type=https</span><br></pre></td></tr></table></figure>

<p>可以看到，当指定使用adaptive extension时，@Adaptive生效，根据URL参数type的值，分别调用了key为http和https的两个扩展类</p>
<h4 id="使用-Activate动态选用扩展类"><a href="#使用-Activate动态选用扩展类" class="headerlink" title="使用@Activate动态选用扩展类"></a>使用@Activate动态选用扩展类</h4><p>了解了@Adaptive的功能之后，@Activate注解的功能也就了然了：在根据URL参数选用扩展类之上，增加了优先级更高的使用group参数选取，并且多个扩展类之间可以指定次序</p>
<p>对应@Activate注解的字段，ExtensionLoader类的getActivateExtension函数允许指定group和key获取扩展类示例</p>
<h3 id="dubbo-SPI加载扩展类流程"><a href="#dubbo-SPI加载扩展类流程" class="headerlink" title="dubbo SPI加载扩展类流程"></a>dubbo SPI加载扩展类流程</h3><p>dubbo扩展类的加载和实例化等操作在ExtensionLoader中进行，其中还涉及到几个类：</p>
<ul>
<li>LoadingStrategy，加载策略接口，可指定扩展类声明文件的路径、包含&#x2F;排除的包名等；LoadingStrategy本身就由java SPI加载实现类来使用——所以说，只要我们自定义一个LoadingStrategy，就可以在其中自定义扩展类声明文件路径等信息</li>
</ul>
<p>扩展类的查找由getExtensionClasses()进而调用loadExtensionClasses()，最终进入了loadDirectory() –&gt; loadDirectoryInternal()，不过最终的查找、解析扩展类声明文件、加载类的方式与java SPI并无大的差异，只是在最终缓存类对象时，根据@Adaptive和@Activate注解使用的不同情况，分类进行了缓存</p>
<h4 id="扩展类的实例化和后置处理"><a href="#扩展类的实例化和后置处理" class="headerlink" title="扩展类的实例化和后置处理"></a>扩展类的实例化和后置处理</h4><p>ExtensionLoader中关键的方法：</p>
<ul>
<li>使用getExtension()方法，默认的加载方式</li>
<li>使用getAdaptiveExtension()方法，处理@Adaptive注解</li>
<li>使用getActivateExtension()方法，处理@Activate注解</li>
</ul>
<p>扩展类的实例化和后置处理中，以createAdaptiveExtension()方法内部为例，关键代码为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 实例化</span></span><br><span class="line"><span class="type">T</span> <span class="variable">instance</span> <span class="operator">=</span> (T) getAdaptiveExtensionClass().newInstance();</span><br><span class="line"><span class="comment">// 类比spring Ioc处理过程中的BeanPostProcessor，调用ExtensionPostProcessor进行初始化前的处理</span></span><br><span class="line">instance = postProcessBeforeInitialization(instance, <span class="literal">null</span>);</span><br><span class="line"><span class="comment">// 对扩展类的setter依赖注入</span></span><br><span class="line">injectExtension(instance);</span><br><span class="line"><span class="comment">// 类比spring Ioc处理过程中的BeanPostProcessor，调用ExtensionPostProcessor进行初始化完成后的处理</span></span><br><span class="line">instance = postProcessAfterInitialization(instance, <span class="literal">null</span>);</span><br><span class="line"><span class="comment">// init操作，处理对象的生命周期</span></span><br><span class="line">initExtension(instance);</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/69a9ed6b.html" rel="prev" title="禅道ZenTao项目管理系统源码包+nginx部署">
      <i class="fa fa-chevron-left"></i> 禅道ZenTao项目管理系统源码包+nginx部署
    </a></div>
      <div class="post-nav-item">
    <a href="/c7e143e.html" rel="next" title="看Spring事务机制的实现">
      看Spring事务机制的实现 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#java-sql-DriverManager%E5%8A%A0%E8%BD%BD%E9%A9%B1%E5%8A%A8%E7%B1%BB%E6%B5%81%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">java.sql.DriverManager加载驱动类流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#java-SPI"><span class="nav-number">2.</span> <span class="nav-text">java SPI</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ServiceLoader%E7%9A%84%E5%8A%A0%E8%BD%BD%E6%96%B9%E5%BC%8F"><span class="nav-number">2.1.</span> <span class="nav-text">ServiceLoader的加载方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#java-SPI%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-number">2.2.</span> <span class="nav-text">java SPI的问题</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#dubbo%E7%9A%84SPI"><span class="nav-number">3.</span> <span class="nav-text">dubbo的SPI</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#dubbo-SPI%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">3.1.</span> <span class="nav-text">dubbo SPI的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#dubbo-SPI%E6%89%A9%E5%B1%95%E7%B1%BB%E7%A4%BA%E4%BE%8B"><span class="nav-number">3.1.1.</span> <span class="nav-text">dubbo SPI扩展类示例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Adaptive%E6%A0%B9%E6%8D%AEURL%E5%8F%82%E6%95%B0%E5%8A%A8%E6%80%81%E9%80%89%E7%94%A8%E6%89%A9%E5%B1%95%E7%B1%BB"><span class="nav-number">3.1.2.</span> <span class="nav-text">使用@Adaptive根据URL参数动态选用扩展类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Activate%E5%8A%A8%E6%80%81%E9%80%89%E7%94%A8%E6%89%A9%E5%B1%95%E7%B1%BB"><span class="nav-number">3.1.3.</span> <span class="nav-text">使用@Activate动态选用扩展类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#dubbo-SPI%E5%8A%A0%E8%BD%BD%E6%89%A9%E5%B1%95%E7%B1%BB%E6%B5%81%E7%A8%8B"><span class="nav-number">3.2.</span> <span class="nav-text">dubbo SPI加载扩展类流程</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%89%A9%E5%B1%95%E7%B1%BB%E7%9A%84%E5%AE%9E%E4%BE%8B%E5%8C%96%E5%92%8C%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86"><span class="nav-number">3.2.1.</span> <span class="nav-text">扩展类的实例化和后置处理</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">马天</p>
  <div class="site-description" itemprop="description">程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/matian2014" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;matian2014" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:matian1103@qq.com" title="E-Mail → mailto:matian1103@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2023001563号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">马天</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
